﻿using System;
using Newtonsoft.Json;

namespace YG.CommonFuncs
{
    /// <summary>
    /// 工具类：对象转换为JSON字符串
    /// </summary>
    public static class Class2Json
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>JSON字符串</returns>

        public static string ToJSON(this object o)
        {
            if (o == null)
            {
                return null;
            }
            return JsonConvert.SerializeObject(o);
        }

        /// <summary>
        /// 把Json文本转为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input"></param>
        /// <returns></returns>
        public static T ToClass<T>(this string input)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(input);
            }
            catch (Exception)
            {
                return default;
            }
        }
    }
}